package ch.uzh.ifi.seal.ssqa.popup.actions;

import java.util.ArrayList;
import java.util.List;

import org.eclipse.emf.common.util.EList;
import org.eclipse.emf.common.util.URI;
import org.eclipse.emf.ecore.EObject;
import org.eclipse.emf.ecore.resource.ResourceSet;
import org.eclipse.emf.ecore.resource.impl.ResourceSetImpl;
import org.eclipse.gmf.runtime.emf.core.resources.GMFResource;
import org.eclipse.jface.action.IAction;
import org.eclipse.jface.viewers.ISelection;
import org.eclipse.swt.widgets.Shell;
import org.eclipse.ui.IActionDelegate;
import org.eclipse.ui.IObjectActionDelegate;
import org.eclipse.ui.IWorkbenchPart;

import ch.uzh.ifi.seal.ssqa.model.Diagram;
import ch.uzh.ifi.seal.ssqa.model.DiagramComponent;
import ch.uzh.ifi.seal.ssqa.model.DiagramComposite;

public class OpenSoftwareAnalysisAction implements IObjectActionDelegate {
	
	Shell shell; 
	
	/**
	 * Constructor for Action1.
	 */
	public OpenSoftwareAnalysisAction() {
		super();
	}

	/**
	 * @see IObjectActionDelegate#setActivePart(IAction, IWorkbenchPart)
	 */
	public void setActivePart(IAction action, IWorkbenchPart targetPart) {
		shell = targetPart.getSite().getShell();
		
		
	}

	/**
	 * @see IActionDelegate#run(IAction)
	 */
	public void run(IAction action) {
		ResourceSet resSet = new ResourceSetImpl();           
		GMFResource resource = (GMFResource) resSet.getResource(URI.createPlatformResourceURI("/Schindler Architecture/architecture.ssqa", true), true);  
		EList<EObject> content = resource.getContents();
		
		List<DiagramComponent> arch = new ArrayList<DiagramComponent>();
		for(EObject object : content){
			
			if(object instanceof Diagram){
				for(DiagramComponent component : ((Diagram)object).getComponents()){
					if(component instanceof DiagramComposite){
						arch.addAll(this.getChildren((DiagramComposite)component));
					} else {
						System.out.println(component.getName() +": "+component.getSourcePaths().toString());
						arch.add(component);
					}
				}
			}
		}
		System.out.println(arch.size());
		System.out.println("These were the Sources of the Components.");
	}

	/**
	 * @see IActionDelegate#selectionChanged(IAction, ISelection)
	 */
	public void selectionChanged(IAction action, ISelection selection) {
	}
	
	private List<DiagramComponent> getChildren(DiagramComposite composite){
		ArrayList<DiagramComponent> comps= new ArrayList<DiagramComponent>();
		System.out.println(composite.getName() +": "+composite.getSourcePaths().toString());
		comps.add(composite);
		if(!composite.getChildren().isEmpty()){
			for(DiagramComponent component : composite.getChildren()){
				if(component instanceof DiagramComposite){
					comps.addAll(this.getChildren((DiagramComposite)component));
				} else {
					System.out.println(component.getName() +": "+component.getSourcePaths().toString());
					comps.add(component);
				}
			}
		}
		return comps;
	}

}
